﻿using System;
using System.IO;
using System.Text;
namespace Com.Common.Cms
{
    public class Log
    {
        public static void RecordLog(String logRoot, Exception e)
        {
            if (String.IsNullOrEmpty(logRoot))
            {
                throw new Exception("日志目录路径为空!(指定一个目录作为日志目录)");
            }
            DateTime now = DateTime.Now;
            String lastLetter = logRoot.Substring(logRoot.Length - 1, 1);
            while (lastLetter == @"\" || lastLetter == @"/")
            {
                lastLetter = logRoot.Substring(logRoot.Length - 1, 1); 
                logRoot = logRoot.Substring(0, logRoot.Length - 1);
            }
            lastLetter += @"\";
            logRoot += now.Year + @"\" + now.Month + @"\" + now.Day+@"\"+ @"\"+now.Hour+@"\";
            if (!Directory.Exists(logRoot))
            {
                Directory.CreateDirectory(logRoot);
            }
            String logFileName = now.Year + "-" + now.Month + "-" + now.Day + "-" + now.Hour  + ".log";
            logRoot += logFileName;
            StringBuilder msg = new StringBuilder(512);
            msg.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n")
                  .Append("Message" + e.Message + "\r\n")
                  .Append("StackTrace:" + e.StackTrace + "\r\n")
                  .Append("Source:" + e.Source + "\r\n")
                  .Append(@"*******************************************************\r\n");

                File.AppendAllText(logRoot, msg.ToString(),Encoding.UTF8);
        }
    }
}
